package com.atguigu.edu.realtime.app.dwd.log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.util.DateFormatUtil;
import com.atguigu.edu.realtime.util.MykafkaUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer;

/**
 * @ClassName DwdTrafficUserNewDetail
 * @Description TODO 流量域 独立访客事务事实表(活跃用户)
 * @Author AFei
 * @Date 2022/9/5 16:39
 * @Version 1.0
 * 需要启动的进程
 *        zk、kafka、flume、DwdTrafficBaseLogSplit、DwdTrafficUniqueVisitorDetail
 */
public class DwdTrafficUserNewDetail {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(4);

        String topic = "dwd_traffic_page_log";
        String groupId = "dwd_traffic_uv_group";
        FlinkKafkaConsumer<String> kafkaConsumer = MykafkaUtil.getKafkaConsumer(topic, groupId);

        DataStreamSource<String> kafkaStrDS = env.addSource(kafkaConsumer);

        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaStrDS.map(JSON::parseObject);

        KeyedStream<JSONObject, String> keyedDS = jsonObjDS.keyBy(jsonObj -> jsonObj.getJSONObject("common").getString("mid"));

        // TODO 过滤出独立访客
        SingleOutputStreamOperator<JSONObject> filterDS = keyedDS.filter(
                new RichFilterFunction<JSONObject>() {
                    private ValueState<String> lastVisitDateState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<String> valueStateDescriptor = new ValueStateDescriptor<>("lastVisitDateState", String.class);
                        valueStateDescriptor.enableTimeToLive(StateTtlConfig.newBuilder(Time.days(1)).build());
                        lastVisitDateState = getRuntimeContext().getState(valueStateDescriptor);
                    }

                    @Override
                    public boolean filter(JSONObject jsonObj) throws Exception {
                        String lastPageId = jsonObj.getJSONObject("page").getString("last_page_id");
                        if (StringUtils.isNotEmpty(lastPageId)) {
                            return false;
                        }
                        String lastVisitDate = lastVisitDateState.value();
                        String curVisitDate = DateFormatUtil.toDate(jsonObj.getLong("ts"));
                        if (StringUtils.isEmpty(lastVisitDate) || !curVisitDate.equals(lastVisitDate)) {
                            lastVisitDateState.update(curVisitDate);
                            return true;
                        }
                        return false;
                    }
                }
        );
        // TODO 将独立访客数据写到kafka主题中
        filterDS.print(">>>>>");
        filterDS.map(jsonObj -> jsonObj.toJSONString())
                .addSink(MykafkaUtil.getKafkaProducer("dwd_traffic_unique_visitor_detail"));

        env.execute();

    }
}
